/**
 * 分级管理
 */
import React, { Component } from 'react';
import { Row, Col, Button, Upload, message, Modal, Input,Form } from 'antd';
import ClassifiesModal from './ClassifiesModal';
import * as Request from '../../Server/SystemManger';
import * as Const from '../../common/const';
import BreadcrumbCustom from '../BreadcrumbCustom';
import * as config from '../../axios/config';
import * as Utils from '../../common/utils';
import qs from 'qs';
import {AuthA,AuthButton} from '../auth/OperationAuth';
import TablePage from "../TablePage";
require('./customer.css');

const confirm = Modal.confirm;
const defaultPage = { page: Const.DEFAULT_PAGE, size: Const.DEFAULT_PAGE_SIZE };
const FormItem = Form.Item;
const success = Modal.success;

class Classifies extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            row: {}, //单条记录信息
            loading: false, //表格加载样式
            data: [], //表格数据
            pagination: {},
            searchText: '',
        };
    }

    componentWillMount() {
        this.getTableData({...defaultPage, name: ''});
    }
    componentWillUnmount() {
        this.setState = () => {return;}
    }
    //获取表格数据
    getTableData = (param) => {
        this.setState({ loading: true });
        const _param = qs.stringify(param);
        Request.getClassifiesPage(_param).then(res => {
            if(res && res.code == Const.REQUEST_SUCCESS){
                const data = res.data;
                this.setState({
                    data: data.content,
                    loading: false,
                    pagination: Object.assign(this.state.pagination, { total: data.totalSize, current: data.page + 1,pageSize:param.size }),
                });
            }else{
                this.setState({ loading: false});
                res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg);
            }
        });
    };
    /* 翻页 */
    handleTableChange = (pagination) => {
        const pager = { ...this.state.pagination };
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        this.setState({
            pagination: pager
        });
        this.getTableData({
            page: pagination.current - 1,//后台分页默认从第0页开始
            size: pagination.pageSize,
            name: this.state.searchText
        });
    }

    //显示或隐藏新增分部方法
    showNewBranch = (row, flag) => {
        this.setState({
            row: row,
            visible: flag
        })
    }

    //删除方法
    deleteFunc = (row) => {
        const param = {
            id: row.id
        };
        const _param = qs.stringify(param);
        confirm({
            title: '确定要删除该条信息？',
            maskClosable: true,
            okText: "确定",
            cancelText: "取消",
            onOk: () => this.onOkFunc(_param),
            onCancel() { },
        });
    }

    //删除确认方法
    onOkFunc = (_param) => {
        Request.deleteClassifies(_param).then(res => {
            if (res && res.code == Const.REQUEST_SUCCESS) {
                this.getTableData(this.getPageParams(true));
                this.getInvalidateFunc();
                message.success('删除成功！', Const.AUTO_DISAPPEAR_TIME);
            } else {
                res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg, Const.ERROR_DISAPPEAR_TIME)
            }
        });
    }

    getPageParams = (isDelete) => {
        const { pagination, searchText } = this.state;
        const params = {
            page: pagination.current -1 ,//后台分页默认从第0页开始
            size: pagination.pageSize || Const.DEFAULT_PAGE_SIZE,
            name: searchText
        };
        if(isDelete && pagination.current == Math.ceil(pagination.total/pagination.pageSize)
            && pagination.total%pagination.pageSize == 1){
            params.page > 0 && params.page --;
        }
        return params;
    }

    //批量导出方法
    outPutFunc = () => {
        Request.outPutClassifies().then(res => {
            const { data, headers } = res;
            const filename = headers['content-disposition'].split("=")[1];
            var blob = new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
            Utils.downloadExcel(blob, '分部信息.xlsx', data);
        })
    }

    //导入成功方法
    importSuccessFunc = (file) => {
        if (file && file.code == Const.REQUEST_SUCCESS) {
            if(file.data&&file.data.length>0){
                let rowItem = file.data.map((item)=>{
                    return <Row className='info-row'>
                        {item.name}
                    </Row>
                })
                success({
                    title: '导入成功，请检查重复分部名称',
                    content: rowItem,
                    maskClosable: true,
                    centered: true,
                    style:{
                        textAlign: 'center'
                    },
                })
            }else{
                message.success('导入成功', Const.AUTO_DISAPPEAR_TIME);
            }
            this.getTableData({ page:0,size: this.currentPageSize() });
            this.getInvalidateFunc();
        } else {
            message.error(file.msg, Const.ERROR_DISAPPEAR_TIME);
        }
    }

    //查询方法
    search = () => {
        const name = this.props.form.getFieldValue('name');
        this.setState({searchText:name,loading:true});
        this.getTableData({page:Const.DEFAULT_PAGE,size:this.currentPageSize(),name:name});
    }

    //重置方法
    reset = () => {
        this.setState({searchText:undefined,loading:true});
        this.props.form.setFieldsValue({name:undefined});
        this.getTableData({page:Const.DEFAULT_PAGE,size:this.currentPageSize()});
    }

    currentPageSize = () => this.state.pagination.pageSize || Const.DEFAULT_PAGE_SIZE;
    //重载缓存方法
    getInvalidateFunc = () =>{
        Request.getInvalidate().then(res => {
            if (res && res.code == Const.REQUEST_SUCCESS) {

            } else {
                res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg, Const.ERROR_DISAPPEAR_TIME);
            }
        })
    }

    render() {
        const { visible, row, loading, data, pagination, searchText } = this.state;
        const {getFieldDecorator} = this.props.form;
        const user = JSON.parse(localStorage.getItem('user'));
        const sysCompany = user?user.sysCompany:{};
        //批量导入配置文件
        const uploaderProps = {
            action: config.COMPANY_IMPORT,
            headers: {
                authorization: 'authorization-text',
            },
            fileList: [],
            onSuccess: this.importSuccessFunc //文件请求完成返回方法
        };

        const columns = [
            {
                title: "分部ID",
                dataIndex: "id",
                key: "id",
                align: 'center',
                width: '20%'
            }, {
                title: "分部名称",
                dataIndex: "name",
                key: "name",
                align: 'center',
                width: '20%',
            }, {
                title: "起始IP段",
                dataIndex: "startIp",
                key: "startIp",
                align: 'center',
                width: '20%'
            }, {
                title: "结束IP段",
                dataIndex: "endIp",
                key: "endIp",
                align: 'center',
                width: '20%'
            }, {
                title: "操作",
                key: "action",
                align: 'center',
                width: '20%',
                render: (text, record) => (
                    <span>
                        <AuthA
                            className='operation-primary'
                            onClick={() => this.showNewBranch(record, true)}
                            permission={'company:save'}
                            >
                            编辑
                        </AuthA>
                        <AuthA
                            className='operation-danger'
                            onClick={() => this.deleteFunc(record)}
                            permission={'company:delete'}
                            >
                            删除
                        </AuthA>
                    </span>
                )
            }
        ];

        return (
            <div>
                <BreadcrumbCustom first={"分级管理"} />
                <Row>
                    <Form  layout="inline" onSubmit={this.search}>
                        <FormItem  label={'分部名称:'}>
                            {getFieldDecorator('name')(
                                <Input maxLength={255}/>
                            )}
                        </FormItem>
                        <FormItem >
                            <Button
                                type="primary"
                                htmlType="submit"
                            >查询</Button>
                            <Button
                                type="default"
                                onClick={this.reset}
                            >重置</Button>
                        </FormItem>
                    </Form>
                </Row>
                <Row>
                    {visible && <ClassifiesModal 
                        sysCompany={sysCompany}
                        showNewBranch={this.showNewBranch} 
                        row={row} 
                        id={row && row.id} 
                        getTableData={this.getTableData} 
                        current={pagination.current}
                        size={this.currentPageSize}
                        getInvalidateFunc={this.getInvalidateFunc}
                        nameText={searchText}
                    />}
                    <Row className="button-margin">
                        <Col {...Utils.getButtonCol('company:save')} className="button-margin">
                            <AuthButton
                                size='large'
                                onClick={() => this.showNewBranch({}, true)}
                                permission={'company:save'}
                            >
                                新增分部
                            </AuthButton>
                        </Col>
                        <Col {...Utils.getButtonCol('company:save')} className="button-margin">
                            <Upload {...uploaderProps}>
                                <AuthButton size='large' permission={'company:save'}>
                                    批量导入
                                </AuthButton>
                            </Upload>
                        </Col>
                        <Col  {...Utils.getButtonCol('company:get')} className="button-margin">
                            <AuthButton size='large' onClick={() => this.outPutFunc()} permission={'company:get'}>
                                批量导出
                            </AuthButton>
                        </Col>
                    </Row>
                    <TablePage
                        dataSource={data}
                        loading={loading}
                        columns={columns}
                        pagination={pagination}
                        onChange={this.handleTableChange}
                    />
                </Row>
                <style>{`
                    .ant-confirm-success .ant-confirm-body > .anticon {
                        margin-left: -65%;
                    }
                    .ant-confirm-success .ant-confirm-body .ant-confirm-title {
                        margin-left: 6%; 
                    }
                `}</style>
            </div>
        )
    }
}
const ClassifiesForm = Form.create()(Classifies);
export default ClassifiesForm;